// pages/archive/newArchive.js
const app = getApp();
const util = require('../../utils/util.js')
import { GET } from '../../utils/methods'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    formList: null,
    defalut: "请选择  >",
    text: "",
    result: {},
    resultArray: [],
    queueId: null,
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '填写建档信息', //导航栏 中间的标题
    },
    navHeight: app.globalData.statusBarHeight * 2 + 86,
    nowDate: new Date(),
    mobile: app.globalData.userMobile,
    userName: null,
    multiArray: [
      [],
      [0, 1, 2, 3, 4, 5, 6]
    ],
    multiIndex: [5, 0],
    maxWeek: 0,
    minWeek: 0,
    multiArrayStr: [
      [],
      ["0天", "1天", "2天", "3天", "4天", "5天", "6天"]
    ],
    birthDate:[],//出生日期
    dueDate:[],//预产期
    gestation:[],//孕周
    committed:false,
    bedNoFlag: true,
    hospitalNoFlag: true, 
    bedFocus: false,
    region: ['上海市', '上海市', '黄浦区'],
    address:{},
    addressCode:'',
    schoolName:'',
    templId:'',
    schoolKey:'',

    popupShow: false,

    value: '',
    schoolList:[],
    pageIndex: 1,
    pageCount: 10,
    templId:'',
    show:false,
    schoolValue:'',
    queueId:''
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function (options) {

        const nowDate = new Date();
        this.data.queueId = options.queueId;
        console.log('options 90',options)
        this.setData({
            schoolName:options.schoolName,
            templId:options.templId,
            schoolKey:options.schoolKey
        })
        if(options.schoolName){
            this.data.result[this.data.schoolKey] = this.data.schoolName
        }
      
      
        GET(app.getUrl('/xcx/pt/createArchive'), {
            templId: options.templId
        }).then(res => {
            if (res.code !== 0) return;

            this.setData({
                mobile: app.globalData.userMobile,
                formList: JSON.parse(res.data),
                nowDate: nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate()
            });
            console.log('formList',this.data.formList)
            this.data.result["Pub1100001"] = this.data.mobile;
            if (this.data.formList == null) return;
            var mutiArr = [
                [],
                [0, 1, 2, 3, 4, 5, 6]
            ];
            var mutiArrStr = [
                [],
                ["0天", "1天", "2天", "3天", "4天", "5天", "6天"]
            ]
            for (var i = 0; i < this.data.formList[0].children.length; i++) {
                var obj = this.data.formList[0].children[i]
                if (obj.type == 'gestation') {
                  this.setData({
                    maxWeek: obj.maxWeek,
                    minWeek: obj.minWeek
                  })
                }
                if (obj.id =="Pub1100004"){
                  this.data.birthDate[0]=i
                } else if (obj.id =="Pub1100005"){
                  this.data.dueDate[0]=i
                } else if (obj.id =="Pub1100006"){
                  this.data.gestation[0]=i
                }
            }
            if (this.data.maxWeek != 0 & this.data.minWeek != 0) {
                for (var i = this.data.maxWeek; i >= this.data.minWeek; i--) {
                  mutiArr[0].push(i)
                  mutiArrStr[0].push(i + "周")
                }
                this.setData({
                    multiArray: mutiArr,
                    multiArrayStr: mutiArrStr,
                })
            }
        });

    },
    toCreateArchive(e){
        console.log('ee222',e)
  
        this.setData({
            popupShow:false,
            schoolName:e.currentTarget.dataset.category.name,
            navbarData:{
                showCapsule:1
            } 
        })
        console.log('this.data.schoolKey',this.data.schoolKey)
        this.data.result[this.data.schoolKey] = this.data.schoolName
        // wx.navigateTo({
        //   url: `/pages/archive/newArchive?schoolName=${e.currentTarget.dataset.category.name}&templId=${this.data.templId}&schoolKey=${this.data.schoolKey}&queueId=${this.data.queueId}`    
        // })
      },
    toSearch(e){
        this.setData({
            popupShow:true,
            schoolKey:e.currentTarget.dataset.key,
            navbarData:{
                showCapsule:0
            }
        })

        this.getNursery()
     
    },
    onSchoolChange(event) {
        this.setData({
            schoolValue:event.detail
        })
        console.log(event.detail);
      },
      showAdd(){
         this.setData({
             show:true,
             schoolValue:''
         })
      },
      add(event) {
          console.log('event',event)
        let that= this
        let param={
            deptId:app.globalData.deptId,
            name:this.data.schoolValue
           }
        wx.request({
            url: app.getUrl('/xcx/pt/insertNursery'),
            method: 'POST',
            data:param,
            success(res) {
                console.log('res',res)
                console.log('res rows',JSON.parse(res.data.data) )
                if (res.data.code == 0) {
                    let msg= JSON.parse(res.data.data).msg
                    wx.showToast({
                      title: '添加成功',
                    })
                  that.setData({
                    value:that.data.schoolValue
                  })
                  that.getNursery()
                }
            }
        })
      },

      onChange(e) {
        this.setData({
          value: e.detail,
        });
      },
    onSearch(){
       console.log('e',this.data.value)
       console.log('app',app.globalData)
       this.getNursery()
    },
    getNursery(){
        let that = this
        let param={
            deptId:app.globalData.deptId,
            name:this.data.value||'幼儿园'
           }
        wx.request({
            url: app.getUrl('/xcx/pt/queryNursery'),
            method: 'POST',
            data:param,
            success(res) {
                console.log('res',res)
                console.log('res rows',JSON.parse(res.data.data) )
                if (res.data.code == 0) {
                        that.setData({
                            schoolList: JSON.parse(res.data.data).rows,
                            pageCount: JSON.parse(res.data.data).total
                        })
                }
            }
        })
    },

    bindDateChange: function (e) {
        console.log('e',e)
        const { key, index } = e.currentTarget.dataset;
        const j = `resultArray[${ index }]`;
        const value = e.detail.value;
        this.data.result[key] = value;
        this.setData({ [j]: value });
        
        if (key === 'Pub1100004') {
            this.data.birthDate[1] = value;
        }

        if (key === 'Pub1100005') {
            this.data.dueDate[1] = value;
        }

        if (this.data.birthDate[1]) {
            this.data.dueDate[1] = this.data.birthDate[1];
            this.data.result['Pub1100005'] = this.data.birthDate[1];
            let index = `resultArray[${ this.data.dueDate[0] }]`;
            this.setData({
                [index]: this.data.birthDate[1],
            })
        }
        this.gestationShow(this.data.birthDate[1], this.data.dueDate[1])
    },
    bindPickerChange: function(e) {
        console.log('e',e)
        const j = 'resultArray[' + e.currentTarget.dataset.index + ']';
        const key = e.currentTarget.dataset.key;
        const value = e.currentTarget.dataset.options[e.detail.value];
        this.data.result[key] = value.key;
        this.setData({
        [j]: value.text
        })
    },
    bindAddressTextInput: function (e) {
        const key = e.currentTarget.dataset.key.id;
        this.setData({
            addressCode:key
        })
        const value = e.detail.value;
        const name = e.currentTarget.dataset.name;
        console.log('eee3',e)
        for (var i = 0; i < e.currentTarget.dataset.key.list.length; i++) {
          var obj = e.currentTarget.dataset.key.list[i];
          if (obj.placeHolder == name) {
            const deCode = obj.deCode;
            this.data.address[deCode] = value;
          }
        }
        console.log(' this.data.result', this.data.address)
      },

      bindRegionChange: function (e) {
        const key = e.currentTarget.dataset.key.id;
        const j = 'resultArray[' + e.currentTarget.dataset.index + ']';
        this.setData({
          [j]: e.detail.value
        })
    
        for (var i = 0; i < e.currentTarget.dataset.key.list.length; i++) {
          var obj = e.currentTarget.dataset.key.list[i];
        //   if (obj.subunit == "省") {
        //     const value = e.detail.value[0];
        //     const deCode = obj.deCode;
        //     const innDeCode = obj.innDeCode;
        //     const resultValue = { val: value, deCode: deCode, innDeCode: innDeCode }
        //     this.data.result[obj.subunit] = resultValue;
        //   }
        //   if (obj.subunit == "市") {
        //     const value = e.detail.value[1];
        //     const deCode = obj.deCode;
        //     const innDeCode = obj.innDeCode;
        //     const resultValue = { val: value, deCode: deCode, innDeCode: innDeCode }
        //     this.data.result[obj.subunit] = resultValue;
        //   }
        //   if (obj.subunit == "区/县") {
        //     const value = e.detail.value[2];
        //     const deCode = obj.deCode;
        //     const innDeCode = obj.innDeCode;
        //     const resultValue = { val: value, deCode: deCode, innDeCode: innDeCode }
        //     this.data.result[obj.subunit] = resultValue;
        //   }
        }
        this.data.result[key] = e.detail.value;
        console.log('e',e)
        console.log('this.data.result[key] ',this.data.result )
      },
    /**
	 * 点击多选框
	 * @param {*} e 
	 */
	handleTapBox: function (e) {
		const { key, value } = e.currentTarget.dataset;
		
		if (this.data.result[key]) {
			if (this.data.result[key].indexOf(value) > -1) {
				this.data.result[key].splice(this.data.result[key].indexOf(value), 1);
			} else {
				this.data.result[key].push(value);
			}
		} else {
			this.data.result[key] = [value];
		}
	},
	handleTapBoxAndInput: function (e) {
        console.log('e',e)
		const { key, value, index, label, i } = e.currentTarget.dataset;
		
        let q = this.data.formList[label].children[i];
        console.log('q',q)
		const relationKey = q.relation;

		if (this.data.result[key]) {
			if (this.data.result[key].indexOf(value) > -1) {
				if (value == relationKey) {
					q.showInput = false;
				}
				this.data.result[key].splice(this.data.result[key].indexOf(value), 1);
				let re = '';
				this.data.result[key].forEach(name => {
					if (q.list.indexOf(name) == -1) re = name;
				})
				this.data.result[key].splice(this.data.result[key].indexOf(re), 1);
			} else {
				if (value == relationKey) q.showInput = true;
				this.data.result[key].push(value);
			}
		} else {
			if (value == relationKey) q.showInput = true;
			this.data.result[key] = [value];
		}
		this.setData({
			result: this.data.result,
			formList: this.data.formList
		})
	},
	handleInputRelation: function (e) {
		const { key } = e.currentTarget.dataset;
		const value = e.detail.value;
		this.data.result[key].push(value);
    },
    bindSchoolName(e){
        // console.log('输入xuex',e)
        // const key = e.currentTarget.dataset.key;
        // this.setData({
        //     schoolKey:key
        // })
        // console.log('key',key)
        // console.log('学校name',this.data.schoolName)
     
        // console.log('jie',this.data)
    },
    bindTextInput: function(e) {
     
    const key = e.currentTarget.dataset.key;
    const value = e.detail.value;
    this.data.result[key] = value;
  },
  showModal: function (text, type) {
    wx.showModal({
        title: '提示',
        content: text,
        confirmText: '重新输入',
        cancelText: '跳过',
        showCancel: false,
        success: (res) => {
            if (res.confirm) {
                
            }
            if (res.cancel) {
                this.data[type] = false;
                this.commitUserInfo();
            }
        },
    })
  },
  commitUserInfo: function(e) {
  
    var that = this;
    let aaa = that.data.result['jd_cstz']
    that.data.result["jd_cstz"] = aaa * 1000
    var retryTime = 0;
    if(Object.keys(this.data.address).length>0){
        let arr = []
        for (const key in  this.data.address) {
            if (Object.hasOwnProperty.call( this.data.address, key)) {
                const element =  this.data.address[key];
                arr.push(element)
            }
        }
        let address=[... this.data.result[this.data.addressCode]]
        console.log('address',address)
        this.data.result[this.data.addressCode] =JSON.stringify([...address,...arr]) 
        console.log('form',that.data.result)
    }
   
    /**
     * 2021 11 15
     * 如果没有住院号 床号时自动添加无
     * 只在 queueId 为 12fddxekyyzzqueue001 生效
     */
  
    if (that.data.queueId === '12fddxekyyzzqueue001') {
        if (that.data.result.Pub12x00008) {
            if (( !that.data.result.Pub12x00008.match(/[0-9]{6}-[0-9]{2}/) || 
                that.data.result.Pub12x00008.length !== 9 ) && that.data.hospitalNoFlag) {
                return that.showModal('住院号需写成 123456-01 的格式', 'hospitalNoFlag');
            }
        }

        if (that.data.result.zcejd_ch) {
            if (that.data.result.zcejd_ch === '+') {
                return that.showModal('床号：固定3位字符(示例：001，+01)', 'bedNoFlag');
            }
            if (!that.data.result.zcejd_ch.match(/(^(\+)[0-9]{2}$)|(^[0-9]{3}$)/) && that.data.bedNoFlag) {
                return that.showModal('床号：固定3位字符(示例：001，+01)', 'bedNoFlag');
            }
        }
    }
  
    setTimeout(function() {
      var list = that.data.formList[0].children;
      
      for (var i = 0; i < list.length; i++) {
            var name = list[i].label
            console.log('that.data.result',that.data.result)
			var obi = that.data.result[list[i].id]
			if (!list[i].rull && (obi == "" || obi == undefined)) {
				wx.showToast({
					title: "请填写" + name,
					icon: 'none',
					duration: 2000
				})
				return false;
			}
        if (list[i].id == "Pub1100006" || list[i].type == "gestation"){
          if (obi > 321 || obi<140 ){
            wx.showToast({
              title: "孕周与出生日期和预产期不匹配",
              icon: 'none',
              duration: 2000
            })
            return false;
          }
        }
        //验证手机号
        if (list[i].id == "Pub1100001"||list[i].type=="mobile") {
            console.log('手机号',obi)
          if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(obi))) {
            wx.showToast({
              title: "手机号码不正确",
              icon: 'none',
              duration: 2000
            })
            return false;
          }
        }
      }
      that.setData({
        committed: true
      })  
      
      wx.showLoading({
        title: "建档中",
        mask: false,
        success() {
          console.log(that.data.result)
          wx.request({
            url: app.getUrl('/xcx/pt/createUserInfo'),
            method: 'POST',
            header: wx.getStorageSync('cookie'),
            data: {
              queueId: that.data.queueId,
              // queueId: "12jmszxyyZCEqueue001",
              content: that.data.result
            },
            success(res) {
              if (res.data.code == 1) {
                that.setData({
                  userName: res.data.data.userName,
                  newArchiveUserId: res.data.data
                })
               that.getUserInfo(retryTime);
              }else {
                wx.showToast({
                  title: res.data.msg||res.data.message,
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          })
        }
      });
      that.setData({
        committed:false
      })
    }, 100)
  },

  bindMultiPickerChange(e) {
    const j = 'resultArray[' + e.currentTarget.dataset.index + ']';
    const key = e.currentTarget.dataset.key;
    const value = e.detail.value;
    this.data.result[key] = this.data.multiArray[0][value[0]] * 7 + this.data.multiArray[1][value[1]]+"";
    this.setData({
      [j]: this.data.multiArrayStr[0][value[0]] + this.data.multiArrayStr[1][value[1]]
    })
    this.data.gestation[1] = this.data.multiArray[0][value[0]] 
    this.data.gestation[2] = this.data.multiArray[1][value[1]]
    this.setData({
      multiIndex: e.detail.value
    })
    this.gestationToDue(this.data.birthDate[1],this.data.result[key])
  },
  bindMultiPickerColumnChange(e) {
    const data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    }
    data.multiIndex[e.detail.column] = e.detail.value
    this.setData(data)
  },
  onClose() {
    this.setData({
         popupShow: false,
         navbarData:{
            showCapsule:1
        } 
        });
  },

  /**
   * 根据出生日期和孕产期计算孕周天数并显示在页面上
   * 如果计算出的孕周天数大于45周6天或者小于20周0天则会显示之前的孕周值
   */
  gestationShow(birth,due){
    if(birth&&due){
      var birthTime = new Date(birth)
      var dueTime = new Date(due)
      var gestationTime = birthTime.getTime() - dueTime.getTime() 
      var gestationDay = 280 + gestationTime / 1000 / 3600 / 24
      // return gestationDay 
      var week = parseInt(gestationDay / 7)
      var day = parseInt(gestationDay % 7)
      var weekIndex = null
      var dayIndex = null
      for (var i = 0; i < this.data.multiArray[0].length; i++) {
        if (week == this.data.multiArray[0][i]) {
          weekIndex = i
        }
      }
      for (var i = 0; i < this.data.multiArray[1].length; i++) {
        if (day == this.data.multiArray[1][i]) {
          dayIndex = i
        }
      }
      if (weekIndex != null && dayIndex != null) {
        this.setData({
          ['resultArray[' + this.data.gestation[0] + ']']: this.data.multiArrayStr[0][weekIndex] + this.data.multiArrayStr[1][dayIndex]
        })
        
      }
      this.data.result["Pub1100006"] = gestationDay + ""
    }
  },
  /**
   * 根据出生日期和孕周修改孕产期
   */
  gestationToDue(birth,gestationDay){
    if (typeof birth != "undefined"){
      var daysDiff = 40 * 7 - gestationDay
      var total = daysDiff*24*3600*1000
      var birthDay = new Date(birth)
      var birthTime = birthDay.getTime()
      var dueTime = util.formatDate(new Date(birthTime + total))
      this.data.dueDate[1] = dueTime
      this.data.result["Pub1100005"] = dueTime +""
      var index = 'resultArray[' + this.data.dueDate[0] + ']'
      this.setData({
        [index]: dueTime,
      })
    }
  },
  /**
   * 根据孕产期和孕周修改出生日期
   */
  gestationToBirth(due, gestationDay){
    if (typeof due != "undefined") {
      var daysDiff = gestationDay-40 * 7
      var total = daysDiff * 24 * 3600 * 1000
      var dueDay = new Date(due)
      var dueTime = dueDay.getTime()
      var birthTime = util.formatDate(new Date(dueTime + total))
      this.data.birthDate[1] = birthTime
      this.data.result["Pub1100004"] = birthTime + ""
      var index = 'resultArray[' + this.data.birthDate[0] + ']'
      this.setData({
        [index]: birthTime,
      })
    }
  },
  getUserInfo(retryTime) {
    console.log('app',app.globalData)
    var that = this;
    var successed = false;
    var interval = setInterval(function () {
      
      wx.request({
        url: app.getUrl('/xcx/pt/newArchiveGetUsersInfo'),
        method: 'GET',
        header: wx.getStorageSync('cookie'),
        data: {
          userName: that.data.userName,
          queueId: that.data.queueId,
          phoneNo:app.globalData.userMobile
        },
        success(res) {
          if (res.data.code == 200||res.data.code == 0) {
            app.globalData.queueId = that.data.queueId
            app.globalData.userId = res.data.message
            app.globalData.userList = res.data.data
            if (!successed){
              successed=true;
              wx.showToast({
                title: "建档成功",
                icon: 'none',
                duration: 1000
              });
            //   let userId =app.globalData.userId
            //   const {  tenantId } = app.globalData.userList.filter(item=>{
            //       return item.id == userId
            //   })[0];
            //   if(tenantId=='klsfybjyzfta001'){
            //     wx.navigateTo({
            //         url: "/pages/advertise/advertise?url=/H5/view-html/scale/html/index.html#/physicalExam" 
            //     })
            //   }else{
            //     wx.reLaunch({
            //         url: "/pages/index/index",
            //       })
            //   }
            wx.reLaunch({
                url: "/pages/index/index",
              })
             
            }
            clearInterval(interval);
          }
          else if (retryTime > 8 ) {
              wx.showToast({
                title: "建档失败或仍在审核中，请稍后重试",
                icon: 'none',
                duration: 1000
              })
              clearInterval(interval);
              if (res.data.code ==0){
                app.globalData.userList = res.data.data
                setTimeout(function () {
                  wx.reLaunch({
                    url: "/pages/index/index",
                  })
                }, 2000)
              }
            }
            else if(res.data.status==404){
                wx.request({
                  url: app.getUrl('/xcx/pt/getUsersInfo'),
                  method: 'GET',
                  header: wx.getStorageSync('cookie'),
                  success(res) {
                    if (res.data.code == 0 || res.data.code == 200) {
                      var flag = false
                      //判断新用户是否建档成功，如果循环结果flag为true，则说明建档成功，反之失败
                      for (var i = 0; i < res.data.data.length; i++) {
                        if (that.data.newArchiveUserId == res.data.data[i].id) {
                          flag = true
                        }
                      }
                      if (flag) {
                        app.globalData.userId = that.data.newArchiveUserId
                        app.globalData.userList = res.data.data
                          wx.showToast({
                            title: "建档成功",
                            icon: 'none',
                            duration: 1000
                          });
                      } else {
                        wx.showToast({
                          title: "建档审核中",
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    //   setTimeout(function () {
                    //     wx.reLaunch({
                    //       url: "/pages/index/index",
                    //     })
                    //   }, 2000)
                      clearInterval(interval);
                    } else {
                      if (retryTime > 8) {
                        wx.showToast({
                          title: "建档失败，请稍后重试",
                          icon: 'none',
                          duration: 1000
                        })
                        clearInterval(interval);
                      } else {
                        retryTime++;
                      }
                    }
                  }
                })
            } else {
              retryTime++;
            }
          }
      })
    }, 1000);
  }
})